package com.light.view;

import atlantafx.base.controls.CustomTextField;
import com.light.component.AuthenticationPane;
import com.light.component.DownloadHBox;
import com.light.enums.Level;
import com.light.model.GitAuthInfo;
import com.light.util.FxApplicationContextUtils;
import com.light.util.H2PoolUtils;
import com.light.util.JGitUtils;
import javafx.beans.property.SimpleStringProperty;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.kordamp.ikonli.antdesignicons.AntDesignIconsOutlined;
import org.kordamp.ikonli.javafx.FontIcon;

import java.io.File;
import java.util.Objects;

import static com.light.util.NoticeUtils.show;

public class HomeView extends BorderPane {

    private final DirectoryChooser dirChooser = new DirectoryChooser();
    private final SimpleStringProperty targetFolderPath = new SimpleStringProperty();
    private final TextField clonePathField = new TextField();
    private final CustomTextField targetPathField = new CustomTextField(targetFolderPath.get());
    private final FontIcon right = new FontIcon(AntDesignIconsOutlined.FOLDER);
    private final Button downloadButton = new Button("下载");

    public HomeView() {
        // 纵向布局
        VBox downloadVBox = new VBox(10);
        downloadVBox.setAlignment(Pos.CENTER);
        // 下载框
        clonePathField.setPromptText("请输入远程项目地址");
        clonePathField.setMaxWidth(600);
        // 目的地框
        targetPathField.setPromptText("请输入本地仓库地址");
        targetPathField.setRight(right);
        targetPathField.setMaxWidth(600);
        // 下载按钮
        downloadButton.setDisable(true);
        downloadVBox.getChildren().addAll(clonePathField, targetPathField, downloadButton);
        this.setCenter(downloadVBox);

        initEvent();
    }

    private void initEvent() {
        downloadButton.setOnAction(btn -> {
            try {
                String remoteUrl = clonePathField.getText();
                String localRepoFile = targetPathField.getText();
                if (StringUtils.isAnyBlank(remoteUrl, localRepoFile)) {
                    show(null, "请检查项目地址和仓库地址不能为空", Level.WARN);
                } else {
                    // 检查仓库地址是不是为空
                    File file = new File(targetPathField.getText());
                    if (file.isFile() || (file.isDirectory() && Objects.requireNonNull(file.listFiles()).length > 0)) {
                        show(null, "仓库地址不为空", Level.WARN);
                        return;
                    }
                    // 检查项目是否已经存在
                    if (H2PoolUtils.existsGitProjects(JGitUtils.getRepoName(remoteUrl), JGitUtils.getAuthor(remoteUrl))) {
                        show(null, "项目已经存在", Level.WARN);
                        return;
                    }
                    // 判断权限信息是否存在
                    GitAuthInfo authInfo = JGitUtils.isExistsAuthInfo(remoteUrl);
                    if (authInfo != null) {
                        FxApplicationContextUtils.DOWNLOAD_LIST.add(new DownloadHBox(remoteUrl, file, authInfo));
                    } else {
                        // 弹出权限界面
                        AuthenticationPane authPane = getAuthenticationPane(remoteUrl, file);
                        authPane.show(getScene());
                    }
                    // 清空信息
                    clonePathField.setText("");
                    targetPathField.setText("");
                    downloadButton.setDisable(true);
                    btn.consume();
                }
            } catch (Exception e) {
                show(null, "下载失败，请稍后重试", Level.DANGER);
            }
        });

        right.setOnMouseClicked(event -> {
            dirChooser.setInitialDirectory(new File(H2PoolUtils.queryDictByLabel("GIT_CURRENT_CLONE_DIR", "") + File.separator));
            File file = dirChooser.showDialog(getScene().getWindow());
            if (null != file) {
                targetFolderPath.set(file.getPath());
                H2PoolUtils.updateDictData("GIT_CURRENT_CLONE_DIR", file.getPath());

                String downloadPathText = clonePathField.getText();
                if (StringUtils.isNotBlank(downloadPathText)) {
                    if (downloadPathText.contains("/") && !downloadPathText.startsWith("/")) {
                        String downloadPathFolder = downloadPathText.substring(downloadPathText.lastIndexOf("/") + 1);
                        String actPath = downloadPathFolder.endsWith(".git") ? downloadPathFolder.substring(0, downloadPathFolder.lastIndexOf(".")) : downloadPathFolder;
                        targetPathField.setText(file.getPath() + File.separator + actPath);
                    } else {
                        targetPathField.setText(file.getPath());
                    }
                } else {
                    targetPathField.setText(file.getPath());
                }
            }
            event.consume();
        });

        clonePathField.setOnKeyReleased(event -> {
            String targetPathText = StringUtils.isBlank(targetFolderPath.get()) ? "" : targetFolderPath.get() + File.separator;
            String downloadPathText = clonePathField.getText();
            if (downloadPathText.contains("/") && !downloadPathText.startsWith("/")) {
                String downloadPathFolder = downloadPathText.substring(downloadPathText.lastIndexOf("/") + 1);
                String actPath = downloadPathFolder.endsWith(".git") ? downloadPathFolder.substring(0, downloadPathFolder.lastIndexOf(".")) : downloadPathFolder;
                if (StringUtils.isNotBlank(targetPathText)) {
                    targetPathField.setText(targetPathText + actPath);
                }
                downloadButton.setDisable(!downloadPathText.endsWith(".git"));
            } else {
                targetPathField.setText(targetPathText);
                downloadButton.setDisable(true);
            }
        });
    }

    @NotNull
    private static AuthenticationPane getAuthenticationPane(String remoteUrl, File file) throws Exception {
        AuthenticationPane authPane = AuthenticationPane.getInstance();
        authPane.refreshData(remoteUrl, (username, password) -> {
            GitAuthInfo authInfo = authPane.dealAuthInfo(username, password, JGitUtils.getType(remoteUrl));
            if (authInfo != null) {
                // 第一次克隆
                FxApplicationContextUtils.DOWNLOAD_LIST.add(new DownloadHBox(remoteUrl, file, authInfo));
            }
        });
        return authPane;
    }
}